package com.violet.constlib;

import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Base64;

import androidx.annotation.NonNull;

import com.violet.constlib.annotations.ConvertMap;
import com.violet.constlib.annotations.Ignore;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Convert {

    public static <S, R> List<R> convertToResultList(List<S> source, @NonNull Class<R> rClass) {
        List<R> results = new ArrayList<R>();
        if(source == null)
            return results;
        try {
            for (S one : source) {
                Constructor<R> constructor = rClass.getConstructor(one.getClass());
                results.add(constructor.newInstance(one));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return results;
    }

    public static @NonNull <S> Map<String, Object> convertToMap(S s) {
        Map<String, Object> map = new HashMap<>();
        Field[] declaredFields = s.getClass().getDeclaredFields();
        if(declaredFields.length == 0) return map;
        for(Field field: declaredFields) {
            field.setAccessible(true);
            Ignore annotation = field.getAnnotation(Ignore.class);
            if(annotation != null) continue;
            ConvertMap convertMap = field.getAnnotation(ConvertMap.class);
            if(convertMap == null) continue;
            String key = field.getName();
            String fKey = convertMap.key();
            if(!TextUtils.isEmpty(fKey)) {
                key = fKey;
            }
            try {
                Object o = field.get(s);
                map.put(key, o);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}

